package com.csun.cmny.provider.service.impl;

import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcRelayAuthDeviceMapper;
import com.csun.cmny.provider.dao.DmcRelayAuthMapper;
import com.csun.cmny.provider.model.domain.DmcRelayAuth;
import com.csun.cmny.provider.model.domain.DmcRelayAuthDevice;
import com.csun.cmny.provider.model.dto.relay.RelayAuthDto;
import com.csun.cmny.provider.service.DmcRelayAuthDeviceService;
import com.csun.cmny.util.PublicUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-11-06 16:50
 * @Description:
 */
@Service
@Transactional
public class DmcRelayAuthDeviceServiceImpl extends BaseService<DmcRelayAuthDevice> implements DmcRelayAuthDeviceService {

    @Resource
    private DmcRelayAuthMapper dmcRelayAuthMapper;
    @Resource
    private DmcRelayAuthDeviceMapper dmcRelayAuthDeviceMapper;

    /**
     * create dmc relay auth with device
     *
     * @param relayAuthDto the relay auth dto
     * @return the int.
     */
    @Override
    public String create(RelayAuthDto relayAuthDto) {

        Long deviceId = relayAuthDto.getDeviceId();
        String username = relayAuthDto.getUsername();
        String password = relayAuthDto.getPassword();

        // 1、查询设备是否已经有认证
        DmcRelayAuth dmcRelayAuth = new DmcRelayAuth();
        dmcRelayAuth.setUsername(username);
        dmcRelayAuth = dmcRelayAuthMapper.selectOne(dmcRelayAuth);
        if (PublicUtil.isNotEmpty(dmcRelayAuth)) {
            return dmcRelayAuth.getPassword();
        }

        // 2、添加设备认证
        dmcRelayAuth = new DmcRelayAuth();
        dmcRelayAuth.setUsername(username);
        dmcRelayAuth.setPassword(password);
        dmcRelayAuth.setCode("device");
        dmcRelayAuthMapper.insertSelective(dmcRelayAuth);

        // 3、绑定设备Id和认证信息
        DmcRelayAuthDevice dmcRelayAuthDevice = new DmcRelayAuthDevice();
        dmcRelayAuthDevice.setDeviceId(deviceId);
        dmcRelayAuthDevice.setRelayAuthId(dmcRelayAuth.getId());

        dmcRelayAuthDeviceMapper.insert(dmcRelayAuthDevice);

        return password;
    }
}
